zz_

src/isPrime.js

zzmq.dev@gmail.com[dev3]/mathkit[add-fibonacci-n-function-returns-nth] / src / isPrime.js @ f12756cf Download
Ladder Summary
  • file Implements and exports isPrime, a function that validates its argument is a finite integer greater than 1 and determines primality by trial division up to the square root, returning true for primes and false otherwise.
/**
 * Determines whether a given number is a prime.
 *
 * @param {number} n - The number to test.
 * @returns {boolean} True if n is a prime integer greater than 1, otherwise false.
 */
export function isPrime(n) {
  if (typeof n !== "number" || !Number.isFinite(n)) return false;
  if (!Number.isInteger(n)) return false;
  if (n < 2) return false;
  if (n === 2) return true;
  if (n % 2 === 0) return false;
  const limit = Math.sqrt(n);
  for (let i = 3; i <= limit; i += 2) {
    if (n % i === 0) return false;
  }
  return true;
}